package net.dotool.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import net.dotool.ConnectionTools;

/**
 * @author 李岩飞
 * @email eliyanfei@126.com	
 * 2018年3月7日 下午2:34:22
 * 
 */
public class SubmitProcess {
	private PreparedStatement ps = null;
	private Connection conn = null;
	private boolean close = false;
	private int count;
	private long total = 1;
	private long error = 0;

	public SubmitProcess(Connection conn, String sql, int count, boolean close) {
		super();
		try {
			this.conn = conn;
			this.close = close;
			this.count = count;
			this.ps = conn.prepareStatement(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public long getError() {
		return error;
	}

	public long getTotal() {
		return total - 1;
	}

	/**
	 * 按数组提交数据
	 * @param datas
	 */
	public void process(Object[] datas) {
		try {
			total++;
			int idx = 1;
			for (Object data : datas) {
				ps.setObject(idx++, data);
			}
			ps.addBatch();
			if (total++ % count == 0) {
				ps.executeBatch();
			}
		} catch (SQLException e) {
			e.printStackTrace();
			error += count;
		} catch (Exception e) {
			e.printStackTrace();
			error++;
		}
	}

	/**
	 * 按集合提交数据
	 * @param datas
	 */
	public void process(List<Object> datas) {
		process(datas.toArray());
	}

	/**
	 * 释放资源
	 */
	public void release() {
		try {
			ps.executeBatch();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			System.out.println("submit totals:" + total + ",errors:" + error);
			ConnectionTools.closeAll(null, ps, close ? conn : null);
		}
	}
}
